package com.sixiaolong.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixiaolong.common.CustomException;
import com.sixiaolong.common.R;
import com.sixiaolong.domain.Category;
import com.sixiaolong.domain.Dish;
import com.sixiaolong.domain.DishDto;
import com.sixiaolong.domain.DishFlavor;
import com.sixiaolong.service.CategoryService;
import com.sixiaolong.service.DishFlavorService;
import com.sixiaolong.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
//    加载dishFlavorService的bean
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
//    @Resource
//    private StringRedisTemplate  redisTemplate;

    /**
     * 新增
     * @param dishDto
     * @return
     */
    @PostMapping()
    public R saveDish(@RequestBody DishDto dishDto){
//        新增菜品需要同时插入菜品对应的口味数据  操作两张表  dish dish_flavor
        dishService.saveWithFlavor(dishDto);
        //        清理所有菜品缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//        清理修改菜品  分类下的的菜品缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
//        redisTemplate.opsForValue().set(key,dishDto);
        return R.success("新增菜品成功");
    }

//    分页
    @GetMapping("/page")
    public R getPage(int page, int pageSize, String name){
        Page<Dish> pageInfe = new Page<>(page,pageSize);
//        因为DishDto不在一张表里 使用该方法查的话会报错 需要拷贝一份dish的分页数据
        Page<DishDto> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(name),Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfe,lqw);
//      对象拷贝 并忽略records属性
        BeanUtils.copyProperties(pageInfe,pageInfo,"records");

        List<Dish> records = pageInfe.getRecords();
        List<DishDto> list = records.stream().map((e) -> {
            DishDto dishDto = new DishDto();
//            把e上的属性都拷贝到dishDto上
            BeanUtils.copyProperties(e,dishDto);
//            分类id
            Long categoryId = e.getCategoryId();
//            根据id查询分类对象
            Category category = categoryService.getById(categoryId);
//            if (category != null){
                String name1 = category.getName();
                dishDto.setCategoryName(name1);
//            }
            return dishDto;
        }).collect(Collectors.toList());
//        records.forEach(e -> {
//            DishDto dishDto = new DishDto();
////            把e上的属性都拷贝到dishDto上
//            BeanUtils.copyProperties(e,dishDto);
////            分类id
//            Long categoryId = e.getCategoryId();
////            根据id查询分类对象
//            Category category = categoryService.getById(categoryId);
//            String name1 = category.getName();
//            dishDto.setCategoryName(name1);
//            return dishDto;
//        });
//        List<DishDto> list = null;
        pageInfo.setRecords(list);
        return R.success(pageInfo);
    }

//    删除菜品
//    @DeleteMapping
//    @Transactional
//    public R<String> deleteData(Long id){
//        dishService.removeById(id);
//        LambdaQueryWrapper<DishFlavor> lqw= new LambdaQueryWrapper<>();
//        lqw.eq(DishFlavor::getDishId,id);
//        dishFlavorService.remove(lqw);
//        return R.success("删除成功");
//    }
//    停售
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable int status, @RequestParam List<Long> ids){
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        log.info("1");

//        Long id = dish.getId();
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.in(dishService::getById,id);
        UpdateWrapper<Dish> uw = new UpdateWrapper<>();
        uw.in("id",ids);
        uw.set("status",status);
        dishService.update(uw);
        //        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//        查询 批量的分类
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids);
        List<Dish> dishList = dishService.list(lqw);
//        遍历 并匹配清除缓存
        dishList.forEach(e -> {
            //        清理修改菜品  分类下的的菜品缓存
            String key = "dish_"+e.getCategoryId()+"_1";
            redisTemplate.delete(key);
//        redisTemplate.opsForValue().set(key,dishDto);
        });
        return R.success("修改成功");
    }

    /**
     * 根据id查询相关菜品信息
     */
    @GetMapping("/{id}")
    public R<DishDto> getDate(@PathVariable Long id){
//        DishDto dishDto = new DishDto();
//        Dish dish = dishService.getById(id);
//        DishFlavor dishFlavor = dishFlavorService.getById(dish.getId());
//        dishDto.getFlavors(dishFlavor);
//        return R.success(dish)
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateData(@RequestBody DishDto dishDto){
        dishService.updateFlavor(dishDto);
//        清理所有菜品缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//        清理修改菜品  分类下的的菜品缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
//        redisTemplate.opsForValue().set(key,dishDto);
        return R.success("修改成功");
    }

//    根据分类id查询菜品名称  可以查询  但是少了口味
//    @GetMapping("/list")
//    public R<List<Dish>> getByIdDish(@RequestParam Long categoryId){
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
////        只查在售的
//        lqw.eq(Dish::getStatus,1);
//        lqw.eq(categoryId != null,Dish::getCategoryId,categoryId);
//        lqw.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> dishes = dishService.list(lqw);
//            return R.success(dishes);
//    }

    //    根据分类id查询菜品名称    菜品口味
    @GetMapping("/list")
    public R<List<DishDto>> getByIdDish(Dish dish){
        List<DishDto> dishDtos = null;
//        获取的是两个参数 categoryId和status  需要拼接
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus(); //dish_1413384954989060097_1
//        先从redis中获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        如果存在则取
        if (dishDtos != null){
            return R.success(dishDtos);
        }
//        不存在则查询数据库  放到redis缓存中
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        只查在售的
        lqw.eq(Dish::getStatus,1);
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        lqw.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = dishService.list(lqw);
        dishDtos = dishes.stream().map(e->{
            DishDto dishDto = new DishDto();
//            把dish 和dishdto 赋值
            BeanUtils.copyProperties(e,dishDto);
            Category category = categoryService.getById(e.getCategoryId());
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId,e.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw1);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        System.out.println(dishDtos);
        System.out.println(dishDtos.toString());
//        不存在则查询数据库  放到redis缓存中
        redisTemplate.opsForValue().set(key, dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);

    }

    /**
     * 批量删除
     */
    @DeleteMapping
    @Transactional
    public R<String> deleteDish(@RequestParam List<Long> id){
//        如果是启售状态  则不能删除
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,id);
        lqw.eq(Dish::getStatus,1);
        int count = dishService.count(lqw);
        if (count>0){
//            说明有启售状态的商品不能删除  抛出异常
            throw new CustomException("有启售状态的菜品，不能删除");
        }
        dishService.removeByIds(id);
        LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
        lqw1.in(DishFlavor::getDishId,id);
        dishFlavorService.remove(lqw1);
        return R.success("删除菜品成功");
    }
/**
 * 文件上传
 */
//    @PostMapping("/upload")
//    public R<String> upload(MultipartFile file){
//
//    }
//    //    分页
//    @GetMapping("/page")
//    public R getPage(int page, int pageSize, String name){
//        Page<Dish> pageInfe = new Page<>(page,pageSize);
//    //        因为DishDto不在一张表里 使用该方法查的话会报错 需要拷贝一份dish的分页数据
//        Page<DishDto> pageInfo = new Page<>(page,pageSize);
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.like(Strings.isNotEmpty(name),Dish::getName,name);
//        lqw.orderByDesc(Dish::getUpdateTime);
//        dishService.page(pageInfe,lqw);
//    //      对象拷贝 并忽略records属性
//        BeanUtils.copyProperties(pageInfe,pageInfo);
//        List<DishDto> records1 = pageInfo.getRecords();
//        records1.forEach(e -> {
//            Category category = categoryService.getById(e.getCategoryId());
//            String name1 = category.getName();
//            e.setCategoryName(name1);
//        });
//        return R.success(pageInfo);
//    }
}



